package com.creatorblue.config.security;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 图形验证码过滤器
 * @author zhuq
 *
 */
public class ValidateCodeFilter extends OncePerRequestFilter{

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		//判断如果是登陆认证请求时，才进行验证码校验逻辑
		if(request.getRequestURI().equals(request.getContextPath() + "/doLogin")) {
			//前端用户输入的验证码
			String ecode = request.getParameter("ecode");
			//会话中生成的验证码
			String code = request.getSession().getAttribute("code").toString();
			//如果两个不一致，则用户输错了
			if(!ecode.equals(code)) {
				request.setAttribute("errorMsg", "验证码错误");
				request.getRequestDispatcher("login").forward(request, response);
				return;
			}
		}
		//放行，接着执行后面的过滤器链
		filterChain.doFilter(request, response);
	}

}
